package com.company.cloud.art.modules.mgr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.constant.ArtErrorEnum;
import com.company.cloud.art.modules.api.request.*;
import com.company.cloud.art.modules.api.response.*;
import com.company.cloud.art.modules.base.entity.ActivityInfo;
import com.company.cloud.art.modules.base.entity.ActivitySignUpInfo;
import com.company.cloud.art.modules.base.service.ActivityInfoService;
import com.company.cloud.art.modules.base.service.ActivitySignUpInfoService;
import com.company.cloud.art.modules.cache.utils.ArtConvertUtils;
import com.company.cloud.art.modules.cache.utils.ArtNoUtils;
import com.company.cloud.art.modules.mgr.service.ActActivityMgrService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.tag.modules.api.response.Label;
import com.company.cloud.tag.modules.api.service.LabelRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

@Service
public class ActActivityMgrServiceImpl implements ActActivityMgrService {

    @Autowired
    private ActivityInfoService activityInfoService;
    @Autowired
    private ActivitySignUpInfoService activitySignUpInfoService;
    @Autowired
    private LabelRemoteService labelRemoteService;

    @Override
    public ActSignUpQueryResp actSignUpQuery(ActSignUpQueryReq request) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime egtTime=null;
        if(StringUtils.hasText(request.getSignUpTimeEgt())) {
            egtTime =LocalDateTime.parse(request.getSignUpTimeEgt(), df);
        }
        LocalDateTime eltTime=null;
        if(StringUtils.hasText(request.getSignUpTimeElt())) {
            eltTime=LocalDateTime.parse(request.getSignUpTimeElt(), df);
        }
        IPage<ActivitySignUpInfo> page = activitySignUpInfoService.page(new Page<>(
                request.getPage(), request.getRows()),
                new QueryWrapper<ActivitySignUpInfo>()
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .eq(StringUtils.hasText(request.getActivityNo()), "activity_no", request.getActivityNo())
                        .like(StringUtils.hasText(request.getName()), "name", request.getName())
                        .like(StringUtils.hasText(request.getNickName()), "nick_name", request.getNickName())
                        .eq(StringUtils.hasText(request.getMobile()), "mobile", request.getMobile())
                        .ge(CheckUtils.hasObj(egtTime), "sign_up_time", egtTime)
                        .le(CheckUtils.hasObj(eltTime), "sign_up_time", eltTime)
        );

        IPage<ActSignUp> data=page.convert(new Function<ActivitySignUpInfo, ActSignUp>() {
            @Override
            public ActSignUp apply(ActivitySignUpInfo entity) {
                return ArtConvertUtils.getActSignUp(entity);
            }
        });

        ActSignUpQueryResp resp = new ActSignUpQueryResp();
        resp.setRecords(data.getRecords());
        resp.setTotal(data.getTotal());
        resp.setPages(data.getPages());
        resp.setSize(data.getSize());
        resp.setCurrent(data.getCurrent());
        return resp;
    }

    @Override
    public ActSignUp actSignUpInfo(Integer id) {
        ActivitySignUpInfo entity= activitySignUpInfoService.getById(id);
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        ActivityInfo act=activityInfoService.getById(entity.getActivityNo());
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        Map<String, Label> labelMap = labelRemoteService.getLabelMapByIds(
                StrSplitUtils.parse2set(act.getTags(),String.class)).getData();

        ActSignUp data=ArtConvertUtils.getActSignUp(entity,act,labelMap);
        return data;
    }

    @Override
    public void actSignUpAdd(ActSignUpAddReq request, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(request);
        ActivityInfo activity=activityInfoService.getById(request.getActivityNo());
        if(activity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(activity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if(BaseConstant.YNEnum.NO.getCode().equals(activity.getIsSignUp())) {
            throw new BusinessException(ArtErrorEnum.ArtActivity_SignUp_Not);
        }

        ActivitySignUpInfo entity=activitySignUpInfoService.getOne(new QueryWrapper<ActivitySignUpInfo>()
                .eq("activity_no",request.getActivityNo())
                .eq("user_id",request.getUserId())
                .eq("rows_state",BaseConstant.EnabledEnum.ENABLED.getCode())
        );

        if(entity==null){
            entity=new ActivitySignUpInfo();
            entity.setActivityNo(request.getActivityNo());
            entity.setUserId(request.getUserId());
            entity.setName(request.getName());
            entity.setNickName(request.getNickName());
            entity.setMobile(request.getMobile());
            entity.setSignUpTime(LocalDateTime.now());
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            activitySignUpInfoService.save(entity);
        }
    }

    @Override
    public ArtActQueryResp actQuery(ArtActQueryReq request) {
        IPage<ActivityInfo> page = activityInfoService.page(new Page<ActivityInfo>(request.getPage(), request.getRows()),
                new QueryWrapper<ActivityInfo>()
                        .eq(StringUtils.hasText(request.getActivityNo()), "activity_no", request.getActivityNo())
                        .like(StringUtils.hasText(request.getTitle()), "title", request.getTitle())
                        .eq(StringUtils.hasText(request.getIsSignUp()), "is_sign_up", request.getIsSignUp())
                        .eq(StringUtils.hasText(request.getCompanyNo()),"company_no",request.getCompanyNo())
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .orderByDesc("edt")
        );

        Set<String> tagIds=new HashSet<String>();
        page.getRecords().forEach(item->{
            Set<String> _tags= StrSplitUtils.parse2set(item.getTags(),String.class);
            tagIds.addAll(_tags);
        });
        Map<String, Label> labelMap = labelRemoteService.getLabelMapByIds(tagIds).getData();

        IPage<ArtAct> data=page.convert(new Function<ActivityInfo, ArtAct>() {
            @Override
            public ArtAct apply(ActivityInfo entity) {
                return ArtConvertUtils.getArtAct(entity,labelMap);
            }
        });

        ArtActQueryResp resp = new ArtActQueryResp();
        resp.setRecords(data.getRecords());
        resp.setTotal(data.getTotal());
        resp.setPages(data.getPages());
        resp.setSize(data.getSize());
        resp.setCurrent(data.getCurrent());
        return resp;
    }

    @Override
    public ArtAct actInfo(String activityNo) {
        ActivityInfo entity=activityInfoService.getById(activityNo);
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        Map<String, Label> labelMap = labelRemoteService.getLabelMapByIds(StrSplitUtils.parse2set(entity.getTags(),String.class)).getData();
        return ArtConvertUtils.getArtAct(entity,labelMap);
    }

    @Override
    public void actAdd(ArtActSaveReq request, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(request);
        ActivityInfo entity=new ActivityInfo();
        entity.setActivityNo(ArtNoUtils.getActivityNo());
        entity.setTitle(request.getTitle());
        entity.setMemo(request.getMemo());
        entity.setCoverImage(StrSplitUtils.list2string(request.getCoverImage()));
        entity.setDetail(request.getDetail());
        entity.setAddr(request.getAddr());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if(!StringUtils.isEmpty(request.getStartTime())) {
            entity.setStartTime(LocalDateTime.parse(request.getStartTime(), df));
        }
        if(!StringUtils.isEmpty(request.getEndTime())) {
            entity.setEndTime(LocalDateTime.parse(request.getEndTime(), df));
        }
        entity.setIsSignUp(request.getIsSignUp());
        entity.setTags(StrSplitUtils.list2string_prefix(request.getTags()));
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        activityInfoService.save(entity);
    }

    @Override
    public void actUpdate(ArtActUpdateReq request, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(request);
        ActivityInfo entity=activityInfoService.getById(request.getActivityNo());
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setTitle(request.getTitle());
        entity.setMemo(request.getMemo());
        entity.setCoverImage(StrSplitUtils.list2string(request.getCoverImage()));
        entity.setDetail(request.getDetail());
        entity.setAddr(request.getAddr());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if(!StringUtils.isEmpty(request.getStartTime())) {
            entity.setStartTime(LocalDateTime.parse(request.getStartTime(), df));
        }
        if(!StringUtils.isEmpty(request.getEndTime())) {
            entity.setEndTime(LocalDateTime.parse(request.getEndTime(), df));
        }
        entity.setIsSignUp(request.getIsSignUp());
        entity.setTags(StrSplitUtils.list2string_prefix(request.getTags()));
        entity.addEditParam(userInfo);
        activityInfoService.updateById(entity);
    }

    @Override
    public void actDel(String activityNo, LoginSimpleUserInfo userInfo) {
        ActivityInfo entity=activityInfoService.getById(activityNo);
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        activityInfoService.updateById(entity);
    }
}
